<template>


<div style="height: 100%">
  <!-- 使用 v-if 确保 homework 存在时才渲染详情 -->
  <div class="homework-detail-content" v-if="homework">
    <h2>{{ homework.subject }}</h2>
    <div class="homework-content" v-html="homework.content"></div>
    <div style="margin-bottom: 20px">
      <span style="font-size: 14px;margin-left: 15px;">截止日期:{{homework.finishdate}}</span>
    </div>

    <div class="homework-info">
      <span style="font-size: 12px">老师：{{ homework.teacherName }}</span>

      <span class="homework-date">日期：{{ formatDate(homework.time) }}</span>
    </div>
  </div>

  <!--对班级信息进行筛选-->
  <div class="class-filter">
    <select v-model="selectedClass">
      <option value="all">全部班级</option>
      <option v-for="cls in classes" :key="cls" :value="cls.className">
        {{ cls.className }}
      </option>
    </select>
  </div>
  <!-- 学生完成情况表格 -->
  <div v-if="studentCompletions.length > 0">
    <table class="completion-table">
      <thead>
      <tr>
        <th>学生姓名</th>
        <th>完成情况</th>
        <th>成绩</th>
        <!-- 添加一个空的<th>来占位，如果有需要 -->
        <th>详情</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="completion in filteredStudentCompletions" :key="completion.studentId" @click="() => goToCorrectHomework(completion)">
        <td>{{ completion.studentName }}</td>
        <td>{{ completion.finish === "1" ? '完成' : '未完成' }}</td>
        <td>{{ completion.score }}</td>
        <!-- 在这里添加图片 -->
        <td class="icon-cell"><img src="../../assets/icons/right.png" alt="Icon"/></td>
      </tr>
      </tbody>
    </table>
  </div>
</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import {Local} from "@/utils/storage";

const classes = ref([]); // 存储所有班级的响应式变量
const selectedClass = ref(null); // 当前选中的班级
// 定义响应式引用
const homework = ref(null);
const studentCompletions = ref([]); // 存储学生完成情况的响应式变量
const router = useRouter(); // 引入 useRouter 钩子
const homeworkId= ref(null);
const teacherId=Local.get('userInfo').userId;


// 进入批改作业页面时，通过路由参数传递数据
const goToCorrectHomework = (studentCompletion) => {
  // 确保 studentCompletion 是一个有效的对象
  if (studentCompletion) {
    router.push({
      name: 'correcthomework',
      params: { studentCompletion: JSON.stringify(studentCompletion) } // 确保传递的是字符串形式
    });
  }
};


//获取班级
const getClasses = async () => {
  try {
    const response = await axios.get(`/api/homework/classes/${teacherId}`);
    classes.value = response.data;
  } catch (error) {
    console.error('Failed to fetch classes:', error);
  }
};
// 组件挂载后执行的逻辑
onMounted(async() => {
  const route = useRoute();
  const homeworkString = route.query.homework;
  await getClasses();
  selectedClass.value = 'all';
  if (homeworkString) {
    try {
      homework.value = JSON.parse(homeworkString);
      // 直接将 homework_id 赋值给 homeworkId ref
      homeworkId.value = homework.value.homeworkId; // 假设 homework_id 是一个数字
    } catch (error) {
      console.error('Error parsing homework data:', error);
      homework.value = { subject: '内容加载失败', content: '', teacherName: '未知', time: '未知' };
    }
  }
  // 确保 homeworkId 有值后再获取学生的完成情况
  if (homeworkId.value) {
    getStudentCompletions(homeworkId.value);
  }

});

//从后端获取学生完成情况数据
const getStudentCompletions = (homeworkIdParam) => {
  axios.get(`/api/homework/completion/${homeworkIdParam}`)
      .then(response => {
        studentCompletions.value = response.data;
        if (!studentCompletions.value.length) {
          console.error('No student completions data received or data format is incorrect.');
        }
      })
      .catch(error => {
        console.error('Failed to fetch student completions:', error);
        studentCompletions.value = []; // 确保在错误时表格不会尝试渲染未定义的数据
      });
};

// 根据选中的班级筛选学生完成情况列表的计算属性
const filteredStudentCompletions = computed(() => {
  return selectedClass.value === 'all'
      ? studentCompletions.value
      : studentCompletions.value.filter(completion => completion.className === selectedClass.value);
});
// 格式化日期的函数
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};
</script>

<style scoped>


.homework-detail-content {
  height: 240px;
  margin: 15px;
  align-items: center; /* 垂直居中子元素 */
  justify-content: space-between; /* 水平分布子元素 */
  border: 2px solid  #9caf70;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影效 */
}

h2 {
  margin: 10px  20px; /* 标题的外边距 */
  font-size: 20px; /* 标题字体大小 */
  margin-left: 15px;
  text-align: center;

}

.homework-content {
  white-space: pre-wrap; /* 保留空白符序列，允许换行 */
  word-wrap: break-word; /* 长单词或不截断的单词将换行 */
  margin-bottom: 30px; /* 内容与下方信息的间距 */
  font-size: 14px;
  margin-left: 15px;
}

/* 作业信息样式 */
.homework-info {
  font-size: 16px; /* 信息字体大小 */
  color: #666; /* 信息字体颜色 */
  margin-bottom: 10px; /* 信息与日期的间距 */
  margin-left: 15px;

}

/* 格式化日期显示 */
.homework-date {
  font-size: 12px; /* 日期字体大小 */
  color: #999; /* 日期字体颜色 */
  margin-left: 60px;
}
/* 表格样式 */
.completion-table {
  width: 90%;
  margin-top: 20px;
  font-size: 14px; /* 设置表格字体大小 */
  margin: 20px auto; /* 添加 auto 值以水平居中表格 */
  border-collapse: collapse; /* 使相邻边框合并为一个边框 */
  border: 2px solid  #9caf70;
}

.completion-table th,
.completion-table td {
  padding: 10px; /* 增加内边距 */
  text-align: center;
  border-bottom: 1px solid #ddd; /* 只保留行与行之间的横线 */

}

/* 表格头部样式 */
.completion-table th {
  background-color: #f5f5f5; /* 为表头添加背景色 */
  color: #333; /* 表头文字颜色 */
  text-align: center; /* 使表头文本居中 */

}

/* 表格行悬浮效果 */
.completion-table tr:hover {
  background-color: #eaeaea; /* 悬浮时的背景色 */
}

/* 图片样式 */
.icon-cell {
  text-align: center; /* 使图片居中显示 */
}

.icon-cell img {
  width: 20px; /* 根据需要设置图片大小 */
  height: auto;
}
.class-filter {
  /* 根据需要添加样式 */
  margin-bottom: 10px;
  margin-left: 20px;
  width: 60%;
  height: auto;
  border-color: #42b983;
}

.class-filter select {
  /* 根据需要添加样式 */
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
}



</style>